import React, { useRef, useState, useEffect } from 'react';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { Image } from "antd";
import { searchUsers } from "@/services/yubi/userController";
import { useModel } from "@umijs/max";
import type { ProColumns, ActionType } from '@ant-design/pro-table';

const columns: ProColumns<API.CurrentUser>[] = [
  {
    dataIndex: 'id',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '昵称',
    dataIndex: 'userName',
    copyable: true,
  },
  {
    title: '用户账号',
    dataIndex: 'userAccount',
    copyable: true,
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    render: (_, record) => (
      <div>
        <Image src={record.userAvatar || '默认头像的URL'} width={40} />
      </div>
    ),
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    valueType: 'select',
    valueEnum: {
      user: { text: '普通用户', status: 'Default' },
      admin: { text: '管理员', status: 'Success' },
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    valueType: 'dateTime',
  },
  {
    title: '操作',
    valueType: 'option',
    render: (text, record, _, action) => [
      <a key="editable" onClick={() => { action?.startEditable?.(record.id); }}>编辑</a>,
      <a href={record.url} target="_blank" rel="noopener noreferrer" key="view">查看</a>,
      <TableDropdown key="actionGroup" onSelect={() => action?.reload()} menus={[
        { key: 'copy', name: '复制' },
        { key: 'delete', name: '删除' },
      ]} />,
    ],
  },
];

export default () => {
  const actionRef = useRef<ActionType>();
  const [allUsers, setAllUsers] = useState<API.CurrentUser[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<API.CurrentUser[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await searchUsers(); // 假设这个函数返回所有用户的数据
        setAllUsers(response.data || []);
        setFilteredUsers(response.data || []);
      } catch (error) {
        console.error("Error fetching users:", error);
      }
    };

    fetchData();
  }, []);

  return (
    <ProTable<API.CurrentUser>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      dataSource={filteredUsers} // 使用filteredUsers作为数据源
      rowKey="id"
      search={{
        labelWidth: 'auto',
        onSearch: (value) => {
          // 实现一个简单的过滤逻辑，根据用户名和用户账号过滤
          const filtered = allUsers.filter(user =>
            user.userName?.includes(value) || user.userAccount?.includes(value)
          );
          setFilteredUsers(filtered);
        },
      }}
      pagination={{
        pageSize: 5,
      }}
      dateFormatter="string"
      headerTitle="用户信息"
    />
  );
};
